# coding:utf-8
import requests
import re
from bs4 import BeautifulSoup
import urllib3
import hashlib
urllib3.disable_warnings()


# 作者：上海-悠悠 QQ交流群：512200893

class LoginLgw():

    def __init__(self, s, url01, url02=''):
        self.s = s
        self.url01 = url01
        self.url02 = url02
        self.h = {"User-Agent": "Mozilla/5.0 (Windows NT 6.2; WOW64; Trident/7.0; rv:11.0) like Gecko",
                  "Accept": "image/gif, image/jpeg, image/pjpeg, application/x-ms-application, application/xaml+xml, application/x-ms-xbap, */*",
                  "Accept-Language": "zh-CN"
                  }

    def getTokenCode(self):
        '''
            <meta name="csrf-token" content="QdvBzR6lBjyIhllQPUh5zU//e7yb80KXNTjjO6WFuVTyqJqgcMVQxi1/ao+d8nwpuLyrTA0IYV7UQglmWU1yvA==">
        '''
        url01 = self.url01
        h=self.h
        # 更新session的headers
        self.s.headers.update(h)
        data = self.s.get(url01, verify=False)
        soup = BeautifulSoup(data.content, "html.parser", from_encoding='utf-8')
        # tokenCode = {}
        try:
            # 提取第二个script的text，从head开始数起
            # t = soup.find_all('script')[1].get_text()
            t01 = soup.find_all('meta')[6]
            t01 = str(t01)
            # 正则表达式，匹配token和Code
            tokenCode= re.findall(r'content="(.+?)"',t01)[0]
        except:
            print("获取token和code失败")
            return None
        else:
            print('获取token成功')
            print(tokenCode)
            return tokenCode

    # md5加密接口
    def encryptPwd(self,passwd):
        # 对密码进行了md5双重加密
        passwd = hashlib.md5(passwd.encode('utf-8')).hexdigest()
        # veennike 这个值是在js文件找到的一个写死的值
        passwd = 'veenike'+passwd+'veenike'
        passwd = hashlib.md5(passwd.encode('utf-8')).hexdigest()
        return passwd

    def login(self,user, psw):
        '''
        function:登录拉勾网网站
        :param user: 账号
        :param psw: 密码
        :return: 返回json
        '''
        gtoken = self.getTokenCode()
        h2 = self.h
        if self.url02 == '':
            url02= self.url01
            # print(url02)
        else:
            url02=self.url02

        body = {"authenticity_token":gtoken,
                "back_url":"http://192.168.175.131/redmine/",
                "username":user,
                "password":psw,
                "login":"登录"
                }
        r2 = self.s.post(url02 , data=body,headers=h2, verify=False)

        # r3 = re.findall(r'登录为(.+?)%s' %user, r2.text)
        # try:
        #     r3[0]
        # except:
        #     print('登录失败！')
        # else:
        #     print('登录成功')
        if '登录为' in r2.text:
            print('登录成功')
        elif '无效的用户名或密码' in r2.text:
            print('账号或密码错误')
        else:
            print('登录失败')
            with open('text01.txt','w',encoding='utf-8') as a01:
                print(a01.writable())
                a01.write(r2.text)

if __name__ == "__main__":
    s = requests.session()
    url01 = 'http://192.168.175.131/redmine/login'
    lgw = LoginLgw(s,url01)
    lgw.login("admin", "dl123456")

    # 目前只获取了之前的token,还没获取登录之后的token